package src

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case

packageName = "" // 基础包名 根据所选择的文件夹自动转换
packageParentName = "" //基础包名的上一级包名

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    // 第三个参数可以设置是否去掉表前缀
    def baseName = javaName(table.getName(), true, true)
    packageName = getPackageName(dir)
    packageParentName = getPackageParentName(packageName)
    // 创建service实现类
    new File("${dir}", baseName + "ServiceImpl.java").withPrintWriter("utf-8") { out -> generateFile(out, baseName) }
}

// 创建service实现类
def generateFile(out, baseName) {
    // 首字母缩写    mapper变量的名字
    lbaseName = Case.LOWER.apply(baseName[0]) + baseName[1..-1]
    out.println "package ${packageName}"
    out.println ""
    out.println "import ${packageParentName}.mapper.${baseName}Mapper;" // 需手动配置
    out.println "import org.springframework.stereotype.Service;"
    out.println "import ${packageParentName}.service.${baseName}Service;"
    out.println "import org.springframework.beans.factory.annotation.Autowired;"
    out.println ""
    out.println "/**"
    out.println " *"
    out.println " * @author lzp" // 可自定义
    out.println " */"
    out.println "@Service"
    out.println "public class ${baseName}ServiceImpl implements ${baseName}Service{" // 可自定义
    out.println ""
    out.println "\t@Autowired"
    out.println "\tprivate ${baseName}Mapper ${lbaseName}Mapper;"
    out.println "}"
}

/**
 *
 * @param str
 * @param capitalize 是否需要开头大写
 * @param needRemovePrefix 是否需要去掉前缀
 * @return
 */
def javaName(str, capitalize, needRemovePrefix) {
    if (needRemovePrefix) {
        def index = str.indexOf("_")
        if (index != null) {
            str = str.substring(str.indexOf("_") + 1)
        }
    }
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

/**
 * 通过选中的文件夹路径获取包名
 * @param dir
 * @return
 */
def getPackageName(dir) {
    return dir.toString()
            .replaceAll("\\\\", ".")
            .replaceAll("/", ".")
            .replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

/**
 * 获取包路径的上一两级路径
 * @param path
 * @return
 */
def getPackageParentName(path) {
    def index = path.lastIndexOf(".")
    if (index != -1) {
        index = path.lastIndexOf(".", index-1)
        if (index != -1) {
            path = path.substring(0, index)
        }
    }
}
